#include<iostream>
#include<ctime>
#include<unistd.h>
#include"Socket.hpp"
#include"Protocol.hpp"
#include"Log.hpp"

using namespace socket_ns;
using namespace log_ns;

int main(int argc,char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }

    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);

    SockSptr sock=std::make_shared<TcpSocket>();
    if(!sock->BuildClientSocket(serverip,serverport))
    {
        std::cerr<<"connect error"<<std::endl;
        exit(1);
    }

    srand(time(nullptr) ^ getpid());
    const std::string opers="+-*/%&^!";
    std::string packagestreamqueue;

    while(true)
    {
        // 构建数据
        int x=rand()%10;
        usleep(x*1000);
        int y =rand()%10;
        usleep(x*y*100);
        char oper=opers[y%opers.size()];

        // 构建请求
        auto req=Factory::BuildRequestDefault();
        req->SetValue(x,y,oper);

        // 序列化
        std::string reqstr;
        req->Serialize(&reqstr);

        // 添加长度报头
        reqstr=Encode(reqstr);
        std::cout<<"--------------------------"<<std::endl;
        std::cout<<"request string: \n"<<reqstr<<std::endl;

        // 发送数据
        sock->Send(reqstr);

        while (true)
        {
            // 读取应答，response
            size_t n = sock->Recv(&packagestreamqueue);
            if (n <= 0)
            {
                break;
            }
            // 报文解析
            std::string package = Decode(packagestreamqueue);
            if (package.empty())
                continue; // 不完整，继续recv
            
            std::cout<<"package: \n"<<package<<std::endl;
            
            // 反序列化
            auto resp=Factory::BuildResponseDefault();
            resp->Deserialize(package);

            // 打印
            resp->PrintResult();

            break;
        }
        sleep(1);
    }
    sock->Close(); // 关闭

    return 0;
}